package utils;

import java.security.NoSuchAlgorithmException;

/**
 * @author xiexiaojin
 * @date 2024-11-19 16:14
 */
public class FastDFSToken {
    /**
     * 生成token
     *
     * @param fileName          the filename return by FastDFS server,不能含有组
     * @param ts 时间戳 单位秒
     * @return token
     * @throws NoSuchAlgorithmException
     */
    private static String generatorToken(String fileName, int ts,String sec_Key) throws Exception {
        byte[] bsFilename = fileName.getBytes("UTF-8");
        byte[] bsTimestamp = (new Integer(ts)).toString().getBytes("UTF-8");
        byte[] bsKey = sec_Key.getBytes("UTF-8");

        byte[] buff = new byte[bsFilename.length + bsKey.length + bsTimestamp.length];
        System.arraycopy(bsFilename, 0, buff, 0, bsFilename.length);
        System.arraycopy(bsKey, 0, buff, bsFilename.length, bsKey.length);
        System.arraycopy(bsTimestamp, 0, buff, bsFilename.length + bsKey.length, bsTimestamp.length);

        return md5(buff);
    }

    public static String md5(byte[] source) throws NoSuchAlgorithmException {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        md.update(source);
        byte tmp[] = md.digest();
        char str[] = new char[32];
        int k = 0;
        for (int i = 0; i < 16; i++) {
            str[k++] = hexDigits[tmp[i] >>> 4 & 0xf];
            str[k++] = hexDigits[tmp[i] & 0xf];
        }

        return new String(str);
    }

    public static String[] getGroupNameAndFileName(String fileurl){
        int index=fileurl.indexOf("/");
        if(index<0){
            return null;
        }
        String[] path={fileurl.substring(0,index),fileurl.substring(index+ 1,fileurl.length())};
        return path;
    }
    public static String autoDownLoadWithToken(String fileUrl,String key,String url_head) throws Exception{
        int ts=(int) (System.currentTimeMillis()/1000);
        String[] arr=getGroupNameAndFileName(fileUrl);
        String fileGroup=arr[0];
        String fileName=arr[1];
        String token=generatorToken(fileName,ts,key);
        return url_head+fileGroup+"/"+fileName+"?token="+token+"&ts="+ts;
    }


}
